package com.sanpu.kxe.business.main.presenter;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;

import com.alibaba.android.arouter.launcher.ARouter;
import com.meiqia.meiqiasdk.util.MQIntentBuilder;
import com.sanpu.kxe.R;
import com.sanpu.kxe.business.main.bean.HomeBannerOutput;
import com.sanpu.kxe.business.main.bean.HomeCenterOutput;
import com.sanpu.kxe.business.main.bean.HomePageOutput;
import com.sanpu.kxe.business.main.bean.InviteMakeMoneyOutput;
import com.sanpu.kxe.business.main.bean.RebateTotalOutput;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.bean.UserConfigOutput;
import com.sanpu.kxe.business.main.contract.HomePageContract;
import com.sanpu.kxe.business.main.contract.MainConfig;
import com.sanpu.kxe.business.main.model.MainModel;
import com.sanpu.kxe.business.main.provider.IMainProvider;
import com.sanpu.kxe.business.main.provider.MainOpenProvider;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.common.utils.ARouterUtils;
import com.sanpu.kxe.module.dialog.GlobalDialog;
import com.sanpu.kxe.rxservice.RequestMap;
import com.sanpu.kxe.utils.IntentTool;
import com.sanpu.kxe.utils.PublicProviderUtil;

import java.util.HashMap;
import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：首页
 * Created by 薛勇军 on 2018/8/2.
 */

public class HomePagePresenter implements HomePageContract.Presenter {

    private HomePageContract.View mView;

    private CompositeSubscription mSubscription;

    private String merchantCode, mName, mTelPhone;

    public HomePagePresenter(HomePageContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void initUserData() {
        UserConfigOutput configOutput = CacheManage.getInstance().getCache(CacheModel.USER_CONFIG);
        if (configOutput != null) {
            mView.showTipsView(configOutput.getMarqueeMainText());
        }
        UserCenterOutput centerOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (centerOutput != null) {
            merchantCode = centerOutput.getMerchantCode();
            if (!TextUtils.isEmpty(centerOutput.getCrpNm())) {
                mName = centerOutput.getCrpNm() + "(" + centerOutput.getUserName() + ")";
            } else {
                mName = centerOutput.getUserName();
            }
            mTelPhone = centerOutput.getUserName();
        }
    }

    @Override
    public void onHomePageItemClick(HomePageOutput output) {
        if (output != null) {
            switch (output.getAppNativeFlg()) {
                case MainConfig.FLAG_OPEN:
                    String appNative = output.getAppNative().getAndroid();
                    if (ARouterUtils.containRouter(appNative)) {
                        ARouter.getInstance()
                                .build(appNative)
                                .withTransition(R.anim.in_from_right, R.anim.in_to_left)
                                .navigation();
                        ARouter.getInstance().build(appNative);
                    }
                    break;
                case MainConfig.FLAG_CLOSED:
                    if (TextUtils.isEmpty(output.getUrl())) return;
                    MainOpenProvider.getInstance().openBrowserX5Activity(mView.getContext(),
                            UrlConstants.getBaseUrl() + output.getUrl(), true);
                    break;
            }
        }
    }

    @Override
    public void onHomeCenterItemClick(HomeCenterOutput output) {
        if (output != null) {
            switch (output.getSkipType()) {
                case MainConfig.SKIPTYPE_NATIVE:
                    String appNative = output.getAppNative().getAndroid();
                    if (ARouterUtils.containRouter(appNative)) {
                        ARouter.getInstance()
                                .build(appNative)
                                .withTransition(R.anim.in_from_right, R.anim.in_to_left)
                                .navigation();
                        ARouter.getInstance().build(appNative);
                    }
                    break;
                case MainConfig.SKIPTYPE_H5:
                    if (TextUtils.isEmpty(output.getUrl())) return;
                    MainOpenProvider.getInstance().openBrowserX5Activity(mView.getContext(),
                            UrlConstants.getBaseUrl() + output.getUrl() + "?" + new RequestMap().map2ReqStr(), true);
                    break;
                case MainConfig.SKIPTYPE_COMINGSOON:
                    new GlobalDialog(mView.getContext())
                            .title("即将上线")
                            .content("敬请期待！")
                            .gravity(Gravity.CENTER)
                            .headerIcon(R.drawable.img_warm_prompt)
                            .show();
                    break;
            }
        }
    }

    @Override
    public void initViewData() {
        getHomePage();
        getBanner();
//        getNewBanner();
        findHomeCenter();
    }

    /**
     * 首页顶部功能栏
     */
    private void getHomePage() {
        mView.showLoadingDialog(true);
        Subscription subscription = MainModel.getInstance().homePage()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<HomePageOutput>>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(List<HomePageOutput> homePageOutputs) {
                        mView.showHomePageView(homePageOutputs);
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 首页banner
     */
    private void getBanner() {
        Subscription subscription = MainModel.getInstance().newBanner()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<HomeBannerOutput>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showBannerView(null);
                    }

                    @Override
                    public void onNext(List<HomeBannerOutput> bannerOutputs) {
                        if (bannerOutputs != null) {
                            for (int i = 0; i < bannerOutputs.size(); i++) {
                                String imageUrl = bannerOutputs.get(i).getImage();
                                bannerOutputs.get(i).setImage(UrlConstants.getBaseUrl() + imageUrl);
                            }
                            CacheManage.getInstance().delete(CacheModel.BANNER);
                            CacheManage.getInstance().saveCache(CacheModel.BANNER, bannerOutputs);
                        }
                        mView.showBannerView(bannerOutputs);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onBannerItemClick(HomeBannerOutput bannerOutput) {
        try {
            if (bannerOutput == null) {
                return;
            }
            switch (bannerOutput.getAppOpenFlg()) {
                case CommonConfig.FLAG_NATIVE:
                    String appNative = bannerOutput.getAppNative().getAndroid();
                    if (ARouterUtils.containRouter(appNative)) {
                        Bundle bundle = new Bundle();
                        bundle.putString(CommonConfig.INTENT_GOODSID, bannerOutput.getGoodsId());
                        ARouter.getInstance()
                                .build(appNative)
                                .withTransition(R.anim.in_from_right, R.anim.in_to_left)
                                .greenChannel()
                                .withBundle(CommonConfig.INTENT_BUNDLE, bundle)
                                .navigation();
                        ARouter.getInstance().build(appNative);
                    }
                    break;
                case CommonConfig.FLAG_HTML:
                    if (TextUtils.isEmpty(bannerOutput.getUrl().getUrl())) return;
                    String url = UrlConstants.getBaseUrl() + bannerOutput.getUrl().getUrl();
                    if (!bannerOutput.getUrl().hasParameter()) {
                        url += "?" + new RequestMap().map2ReqStr();
                    }
                    IMainProvider provider = PublicProviderUtil.getProvider(IMainProvider.class);
                    if (provider != null) {
                        provider.openBrowserX5Activity(mView.getContext(), url,
                                bannerOutput.getUrl().hasTitle(), true);
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 首页中间功能栏
     */
    private void findHomeCenter() {
        Subscription subscription = MainModel.getInstance().findHomeCenter()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<HomeCenterOutput>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(List<HomeCenterOutput> homeCenterOutputs) {
                        mView.showHomeCenterView(homeCenterOutputs);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void conversationWrapper() {
        if (ContextCompat.checkSelfPermission(mView.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((Activity) mView.getContext(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    CommonConfig.WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
        } else {
            HashMap<String, String> clientInfo = new HashMap<>();
            clientInfo.put("name", mName);
            clientInfo.put("tel", mTelPhone);
            HashMap<String, String> updateInfo = new HashMap<>();
            updateInfo.put("name", mName);
            Intent intent = new MQIntentBuilder(mView.getContext())
                    .setClientInfo(clientInfo)
                    .updateClientInfo(updateInfo)
                    .setCustomizedId(merchantCode)
                    .build();
            IntentTool.startActivity(mView.getContext(), intent);
        }
    }

    @Override
    public void inviteMakeMoney() {
        Subscription subscription = MainModel.getInstance().inviteMakeMoney()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<InviteMakeMoneyOutput>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(List<InviteMakeMoneyOutput> inviteFriendsOutputs) {
                        mView.showInviteMakeMoneyData(inviteFriendsOutputs);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void getRebateTotal() {
        Subscription subscription = MainModel.getInstance().rebateTotal()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RebateTotalOutput>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showRebateTotalView(null);
                    }

                    @Override
                    public void onNext(RebateTotalOutput output) {
                        if (output != null) {
                            CacheManage.getInstance().saveCache(CacheModel.REBATETOTAL, output);
                        }
                        mView.showRebateTotalView(output);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
